import { ref, onMounted, onUnmounted } from 'vue';
import { Message } from '@arco-design/web-vue';

export default function useWebSocket(url: string) {
  const socket = new WebSocket(url);
  const message = ref<any[]>([]);

  const connect = () => {
    socket.onopen = () => {
      console.log('WebSocket打开');
    };
    socket.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.Success) {
        message.value = data;
      } else {
        Message.warning(data.ErrorMessage);
      }
    };
    socket.onclose = () => {
      console.log('WebSocket关闭');
    };
  };

  const sendMessage = (v: string) => {
    if (socket.readyState === WebSocket.OPEN) {
      socket.send(v);
    }
  };
  const dispose = () => {
    socket.close();
  };

  onMounted(connect);
  onUnmounted(dispose);

  return { message, sendMessage };
}
